#include "disp.h"
#include "rtc.h"
#include "sht.h"
#include "bitmap.h"
#include "wifi.h"
#include "ClosedCube_SHT31D.h"

NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> strip(256, 3);
RgbColor color(0, 0, 0);
uint32_t COLOR = 0;
float brightness = 0;
uint32_t disp_buf[8][32];

extern SHT31D sht_res;

void rgbInit(void)
{
    strip.Begin();   
    strip.Show();
    // setBrightness(DEFAULT_BRIGHTNESS);
}

void drawPoint(int8_t x, int8_t y, uint8_t en)
{
    if(x>=0 && x<32 && y>=0 && y<8)
        disp_buf[y][x] = COLOR*en;
}

uint8_t drawChar(char c, int8_t x, int8_t y, uint8_t height)
{
    uint8_t i = 0, j = 0, a = 0, weight = 0;
    uint8_t t, x1, y1;

    x1 = x;
    y1 = y;
    a = c - ' ';

    for(i=0; i<height; i++, y1++, x1 = x)
    {
        t = pgm_read_byte_far(&font[a][i]);
        for(j=0; j<8; j++, x1++)
        {
            // if(x1 > 31)
            //     break;
            drawPoint(x1, y1, (t&0x80)>>7);
            t <<= 1;
        }
    }
    weight = pgm_read_byte_far(&font[a][5]);
    return weight;
}

void drawNum(uint8_t num, int8_t x, int8_t y)
{
    uint8_t pos = 0;
    pos = drawChar(num/10+48, x, y, 5);
    pos = drawChar(num%10+48, x+pos+1, y, 5);
}

void drawString(char *p, int8_t x, int8_t y)
{
	char *ps;
    uint8_t pos = 0;

	while(1)
	{
		ps = p++;
		pos = drawChar(*ps, x, y, 5);
		x += (pos+1);
		if(*p=='\0' || x>31)		
			break;
	}
}

void drawBitmapRGB(const uint32_t *p, int8_t x, int8_t y, uint8_t w, uint8_t h)
{
    int8_t x1, y1, w1, h1, i;
    uint8_t *u8_p;
    u8_p = (uint8_t*)p;

    w1 = x+w;
    h1 = y+h;
    
    for(y1=y; y1<h1; y1++, x1 = x)
    {
        for(x1=x; x1<w1; x1++, i++)
        {
            setColor((uint8_t)(p[i]>>16), (uint8_t)((p[i]>>8)&0xFF), (uint8_t)(p[i]&0xFF));
            // setColor(pgm_read_byte_far(u8_p), pgm_read_byte_far(u8_p+1), pgm_read_byte_far(u8_p+2));
            drawPoint(x1, y1, 1);
        }
    }
}

void disp(void)
{
    uint8_t i = 0, j = 0;
    uint32_t col = 0;

    for(i=0; i<32; i++)
    {
        for(j=0; j<8; j++)
        {
            col = disp_buf[j][i];
            color.R = (col>>16) & 0x000000FF;
            color.G = (col>>8) & 0x000000FF;
            color.B = col & 0x000000FF;
            if(i%2 == 0)
                strip.SetPixelColor(8*i+j, color);
            else
                strip.SetPixelColor(8*(i+1)-1-j, color);
        }
    }
    strip.Show();
}

void dispClear(void)
{
    uint8_t i, j;
    for(i=0; i<8; i++)
        for(j=0; j<32; j++)
            disp_buf[i][j] = 0;
}

